package com.daisuxia.back.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daisuxia.back.service.IRiskUserService;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskRuleCal;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ObtainUserShortMessage;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserContacts;
import com.daisuxia.web.pojo.UserInfoImage;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IObtainUserShortMessageService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserContactsService;
import com.daisuxia.web.service.IUserInfoImageService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.PageConfig;

@Controller
@RequestMapping("userManage/")
public class UserManageController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(UserManageController.class);
	@Autowired
	public IUserService userService;
	@Autowired
	public IUserBankService userBankService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserInfoImageService userInfoImageService;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IObtainUserShortMessageService userShortMessageService;
	
	@Autowired
	@Qualifier("riskUserService")
	private IRiskUserService riskUserService;
	
	/**
	 * 用户管理 --》用户列表 
	 */
	@RequestMapping("gotoUserManage")
	public String gotoUserManage(HttpServletRequest request,HttpServletResponse response,Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			String userId=request.getParameter("id");
			String status=request.getParameter("status");
			String realname=request.getParameter("realname");
			String idNumber=request.getParameter("idNumber");
			String userPhone=request.getParameter("userPhone");
			String createTime=request.getParameter("createTime");
			String beginTime=request.getParameter("beginTime");
			PageConfig<User> page = this.userService.getUserPage(params);
			if(StringUtils.isBlank(userId)){userId=null;}
			if(StringUtils.isBlank(status)){status=null;}
			if(StringUtils.isBlank(realname)){realname=null;}
			if(StringUtils.isBlank(idNumber)){idNumber=null;}
			if(StringUtils.isBlank(userPhone)){userPhone=null;}
			if(StringUtils.isBlank(createTime)){createTime=null;}
			if(StringUtils.isBlank(beginTime)){beginTime=null;}
			if(!StringUtils.isBlank(userId)|| null!=userId || !StringUtils.isBlank(userPhone) || null!=userPhone || !StringUtils.isBlank(status) || null!=status || !StringUtils.isBlank(realname) || null!=realname || !StringUtils.isBlank(idNumber) || null!=idNumber|| !StringUtils.isBlank(createTime) || null!=createTime || !StringUtils.isBlank(beginTime) || null!=beginTime){
				//page=this.userService.getUserPage(params);		
			}
			model.addAttribute("pm", page);
			model.addAttribute("searchParams", params);//用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/userManageList";//用户列表jsp
	}
	
	/**
	 * 用户管理 --》用户列表 --》 操作
	 */
	@RequestMapping("operation")
	public void operation(HttpServletRequest request,HttpServletResponse response,Model model) {
		boolean bool = false;
		try {
			String id=request.getParameter("id");
			if(request.getParameter("option").equals("1")){//黑名单
				User user=new User();
				user.setId(id);
				user.setStatus("2");//2黑名单
				int count=this.userService.updateByPrimaryKeyUser(user);
				if(count>0){
					bool=true;
				}
			}else if(request.getParameter("option").equals("2")){//注销/删除资料账户
				User user=this.userService.searchByUserid(Integer.parseInt(id));
				if(!StringUtils.isBlank(user.getUserName())){
					user.setUserName(user.getUserName()+"*");
				} 
				if(!StringUtils.isBlank(user.getIdNumber())){
					user.setIdNumber(user.getIdNumber()+"*");
				} 
				if(!StringUtils.isBlank(user.getUserPhone())){
					user.setUserPhone(user.getUserPhone()+"*");
				} 
				user.setStatus("3");//3 删除
				HashMap<String, Integer> map=new HashMap<String, Integer>();
				map.put("id", Integer.parseInt(id));
				int count=this.userService.deleteByPrimaryKeyUser(map);
				if(count>0){
					bool=true;
				}
			}else if(request.getParameter("option").equals("3")){//保存修改手机号码
				User user=new User();
				user.setId(id);
				user.setUserName(request.getParameter("userPhone"));//用户名称
				user.setUserPhone(request.getParameter("userPhone"));//用户手机号码
				int count=this.userService.updateByPrimaryKeyUser(user);
				if(count>0){
					bool=true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpringUtils.renderDwzResult(response, bool, bool ? "操作成功" : "操作失败", DwzResult.CALLBACK_CLOSECURRENT);
	
	}
	
	/**
	 * 新旧号码更改
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userManagePhone")
	public String userManagePhone (HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		User user=this.userService.searchByUserid(Integer.parseInt(params.get("id")));
		model.addAttribute("id",user.getId());
		model.addAttribute("userPhone",user.getUserPhone());
		return "userInfo/userManageUpdatePhone";
	}
	
	/**
	 * 用户通讯录  
	 */
	@RequestMapping("gotoUserContacts")
	public String gotoUserContacts(HttpServletRequest request,HttpServletResponse response,Model model){
		HashMap<String, Object> params =this.getParametersO(request);
		PageConfig<UserContacts> contacts=this.userContactsService.selectUserContactsList(params);
		model.addAttribute("pm", contacts);
		model.addAttribute("searchParams", params);//用于搜索框保留值
		
		return "userInfo/userManagePhone";
	}
	
	/**
	 * 用户短信列表  
	 */
	@RequestMapping("gotoUserShortMsg")
	public String gotoUserShortMsg(HttpServletRequest request,HttpServletResponse response,Model model){
		HashMap<String, Object> params =this.getParametersO(request);
		PageConfig<ObtainUserShortMessage> contacts=this.userShortMessageService.selectUserShortMsgList(params);
		model.addAttribute("pm", contacts);
		model.addAttribute("searchParams", params);//用于搜索框保留值
		
		return "userInfo/userManageShortMsg";
	}
	
	
	/**
	 * 用户详情
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userdetails")
	public String userdetails (HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		User user= userService.searchByUserid(Integer.parseInt(params.get("id")));
		String cardNo=user.getIdNumber();
		if(cardNo!=null&&cardNo.length()>=18){
			String yy= cardNo.substring(6,10); //出生的年份
			String mm= cardNo.substring(10,12); //出生的月份
			String dd = cardNo.substring(12,14); //出生的日期 
			String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
			model.addAttribute("birthday",birthday);
			model.addAttribute("age", SpringUtils.calculateAge(birthday,"yy-MM-dd"));

		}
		user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
		user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
		user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
		user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
		user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
		model.addAttribute("user",user);
		BorrowOrder borrowOrderLastest = borrowOrderService.selectBorrowOrderUseId(Integer.parseInt(params.get("id")));
		model.addAttribute("borrow", borrowOrderLastest);
		
		if(null!=borrowOrderLastest){
			// 查询征信信息
			System.out.println("id:"+borrowOrderLastest.getId());
			RiskCreditUser riskCreditUser = riskUserService.findRiskCreditUserByAssetsId(String.valueOf(borrowOrderLastest.getId()));
			if (null != riskCreditUser) {
				model.addAttribute("riskCreditUser", riskCreditUser);
			}

			// 规则查询
			List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByAssetsId(String.valueOf(borrowOrderLastest.getId()));
			model.addAttribute("riskRuleCalList", riskRuleCalList);
		}
		UserCardInfo daisuxia=userService.findUserBankCard(Integer.parseInt(params.get("id")));
		model.addAttribute("bankCard",daisuxia);
		List<UserInfoImage> userInfoImage=this.userInfoImageService.selectImageByUserId(Integer.parseInt(params.get("id")));
		model.addAttribute("daisuxiaImage", userInfoImage);
		HashMap<String, Object> paramsM = new HashMap<String, Object>();
		paramsM.put("userId",user.getId());
		paramsM.put("statusList", new int[]{20,21,22,23,30,-20,-11});
		PageConfig<BorrowOrder> userBorrows = borrowOrderService.findPage(paramsM);
		model.addAttribute("userBorrows", userBorrows);
		model.addAttribute("params", params);
		return "userInfo/userdetails";
	}
	
	@RequestMapping("updadteBankCard")
	public String updadteBankCard(HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		UserCardInfo daisuxia=userService.findUserBankCard(Integer.parseInt(params.get("id")));
		model.addAttribute("bankIndo", daisuxia);
		List<Map<String,Object>> mapList=userBankService.findAllBankInfo();
		model.addAttribute("bankList", mapList);
		model.addAttribute("params", params);
		return "userInfo/updadteBankCard";
	}
	
	/**
	 * 重新绑定银行卡
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("updateBankCard")
	public void updateBankCard(HttpServletRequest request,HttpServletResponse response,Model model){
		boolean bool=false;
		JsonResult result=null;
		try{
				Map<String,String> pams=this.getParameters(request); 
				result=userBankService.updateUpserBankCard(pams);
				if(result.isSuccessed()){
					bool=true;
				}
		}catch (Exception e) {
			result=new JsonResult("500","系统异常请稍后重试");
			e.printStackTrace();
		}finally{
			SpringUtils.renderDwzResult(response, bool, bool ? "操作成功": result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT);
		}
	}
	
	public int calculateAge(String birthday,String format){
		int age=0;
		try {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date today = sdf.parse(birthday);
			age=date.getYear()-today.getYear();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return age;
	}
	
	/**
	 * 银行卡列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userBankCardList")
	public String userBankCardList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			String userId=request.getParameter("userId");
			String userName=request.getParameter("userName");
			String userPhone=request.getParameter("userPhone");
			String cardNo=request.getParameter("cardNo");
			String status=request.getParameter("status");
			String addStartTime=request.getParameter("addStartTime");
			String addEndTiem=request.getParameter("addEndTiem");
			if(StringUtils.isBlank(userId)){userId=null;}
			if(StringUtils.isBlank(userName)){userName=null;}
			if(StringUtils.isBlank(userPhone)){userPhone=null;}
			if(StringUtils.isBlank(cardNo)){cardNo=null;}
			if(StringUtils.isBlank(status)){status=null;}
			if(StringUtils.isBlank(addStartTime)){addStartTime=null;}
			if(StringUtils.isBlank(addEndTiem)){addEndTiem=null;}
			
			PageConfig<Map<String,String>> pageConfig=userBankService.findAllUserBankCardList(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userBankCardList";
	}
	/**
	 * 实名认证列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userRealNameList")
	public String userRealNameList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			PageConfig<Map<String,String>> pageConfig=userService.realNmaeList(params);
			model.addAttribute("pm", pageConfig);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userRealNameList";
	}
	/**
	 * 用户认证列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userCertificationList")
	public String userCertificationList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			
			
			PageConfig<Map<String,String>> pageConfig=userService.certificationList(params);
			
			List<Map<String, String>> list=pageConfig.getItems();
			List<Map<String, String>> tempList=new ArrayList<Map<String, String>>();
			boolean bool=false;
			Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
			for (Map<String, String> map : list) {
					// 规则查询
				    String userId=String.valueOf(map.get("userId"));
					List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByUserId(userId);
					boolean a=false;
					if(riskRuleCalList!=null && riskRuleCalList.size()>0) {
						for (RiskRuleCal riskRuleCal : riskRuleCalList) {
					    	a=p.matcher(riskRuleCal.getRuleValue()).find();
					    	if(a) {
					    		map.put("flag", "用户机审规则不通过");
					    		map.put("describe", riskRuleCal.getRuleValue());
					    		bool=true;
					    		break;
					    	}
						}
						if(!bool) {
							map.put("flag", "用户机审规则通过");
				    		map.put("describe", "");
						}
					}else {
						map.put("flag", "");
			    		map.put("describe", "用户未走机审规则");
					}
					
				tempList.add(map);
			}
			pageConfig.setItems(tempList);
			model.addAttribute("pm", pageConfig);
	
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userCertificationList";
	}
	
	/**
	 *用户通讯录列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("addressBookList")
	public String addressBookList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			String userId=request.getParameter("userId");
			String userPhone=request.getParameter("userPhone");
			String contactPhone=request.getParameter("contactPhone");
			String contactName=request.getParameter("contactName");
			if(StringUtils.isBlank(userId)){userId=null;}
			if(StringUtils.isBlank(userPhone)){userPhone=null;}
			if(StringUtils.isBlank(contactPhone)){contactPhone=null;}
			if(StringUtils.isBlank(contactName)){contactName=null;}
			PageConfig<UserContacts> pageConfig=userContactsService.selectUserContactsList(params);
			if(!StringUtils.isBlank(userId)|| null!=userId || !StringUtils.isBlank(userPhone) || null!=userPhone || !StringUtils.isBlank(contactName) || null!=contactName){
				//pageConfig=userContactsService.selectUserContactsList(params);				
			}
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/addressBookList";
	}
}
